package model

import (
	"fmt"
	"wlblog/src/utils/errmsg"

	"gorm.io/gorm"
)

type User struct {
	gorm.Model
	UserName string `gorm:"type:varchar(20);not null" json:"username" binding:"required"`
	Password string `gorm:"type:varchar(20);not null" json:"password" binding:"required"`
	Role     int    `gorm:"type:int" json:"role"`
}

func (User) TableName() string {
	return "user"
}

func (u *User) Exist() int {
	var user User
	err := db.Select("id").Where("user_name = ?", u.UserName).First(&user).Error
	if err != nil && err.Error() != "record not found" {
		fmt.Printf("查询用户名失败：%v\n", err)
	}
	if user.ID > 0 {
		return errmsg.USER_EXIST
	}
	return errmsg.USER_NOT_EXIST
}

func (u *User) Create() int {
	if code := u.Exist(); code == errmsg.USER_EXIST {
		return code
	}
	if err := db.Create(&u).Error; err != nil {
		fmt.Printf("创建用户失败：%v\n", err)
		return errmsg.ERROR
	}
	return errmsg.SUCCE
}

func GetUser(id uint) (*User, int) {
	var user *User
	err := db.Limit(1).Where("id = ?", id).First(&user).Error
	if err != nil {
		fmt.Printf("查询用户信息失败：%v\n", err)
		return nil, errmsg.ERROR
	}
	return user, errmsg.SUCCE
}

func GetUsers(userName string, pageSize, currPage int) ([]User, int64) {
	var users []User
	var total int64

	if userName != "" {
		db.Where("user_name LIKE ?", userName+"%").
			Limit(pageSize).Offset((currPage - 1) * pageSize).
			Find(&users)
		db.Model(&users).
			Where("user_name LIKE ?", userName+"%").
			Count(&total)
		return users, total
	}

	db.Limit(pageSize).Offset((currPage - 1) * pageSize).Find(&users)
	db.Model(&users).Count(&total)
	return users, total
}
